import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Image,
  Alert,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { RNCamera } from 'react-native-camera';
import Icon from 'react-native-vector-icons/MaterialIcons';

const DocumentScanScreen = ({ navigation, route }) => {
  const { documentType } = route.params;
  const [hasPermission, setHasPermission] = useState(null);
  const [scannedImage, setScannedImage] = useState(null);
  const [isScanning, setIsScanning] = useState(true);

  useEffect(() => {
    // 请求相机权限
    requestCameraPermission();
  }, []);

  const requestCameraPermission = async () => {
    try {
      // 这里应该使用实际的权限请求库
      setHasPermission(true);
    } catch (err) {
      console.warn(err);
      setHasPermission(false);
    }
  };

  const handleTakePicture = async () => {
    if (this.camera) {
      const options = { quality: 0.5, base64: true };
      const data = await this.camera.takePictureAsync(options);
      setScannedImage(data.uri);
      setIsScanning(false);
    }
  };

  const handleRetake = () => {
    setScannedImage(null);
    setIsScanning(true);
  };

  const handleContinue = () => {
    if (documentType === 'id_card' || documentType === 'driver_license') {
      // 如果是身份证或驾驶证，需要扫描背面
      if (!scannedImage) {
        Alert.alert('提示', '请先拍摄证件正面');
        return;
      }
      navigation.navigate('UserInfoCollection', {
        documentType,
        frontImage: scannedImage,
      });
    } else {
      // 护照只需要正面
      navigation.navigate('UserInfoCollection', {
        documentType,
        image: scannedImage,
      });
    }
  };

  if (hasPermission === null) {
    return (
      <LinearGradient colors={['#1a1a2e', '#16213e']} style={styles.container}>
        <View style={styles.permissionContainer}>
          <Text style={styles.permissionText}>请求相机权限...</Text>
        </View>
      </LinearGradient>
    );
  }

  if (hasPermission === false) {
    return (
      <LinearGradient colors={['#1a1a2e', '#16213e']} style={styles.container}>
        <View style={styles.permissionContainer}>
          <Text style={styles.permissionText}>需要相机权限才能扫描证件</Text>
          <TouchableOpacity style={styles.permissionButton}>
            <Text style={styles.permissionButtonText}>授予权限</Text>
          </TouchableOpacity>
        </View>
      </LinearGradient>
    );
  }

  return (
    <LinearGradient colors={['#1a1a2e', '#16213e']} style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        <Text style={styles.title}>扫描证件</Text>
        <Text style={styles.subtitle}>
          请将证件放置在框内，确保清晰可见
        </Text>

        {isScanning ? (
          <View style={styles.cameraContainer}>
            <RNCamera
              ref={(ref) => (this.camera = ref)}
              style={styles.camera}
              type={RNCamera.Constants.Type.back}
              captureAudio={false}
            >
              <View style={styles.cameraOverlay}>
                <View style={styles.scanFrame} />
                <Text style={styles.scanHint}>请将证件放在框内</Text>
              </View>
            </RNCamera>
          </View>
        ) : (
          <View style={styles.previewContainer}>
            <Image source={{ uri: scannedImage }} style={styles.previewImage} />
            <TouchableOpacity style={styles.retakeButton} onPress={handleRetake}>
              <Icon name="camera-alt" size={24} color="#fff" />
              <Text style={styles.retakeText}>重新拍摄</Text>
            </TouchableOpacity>
          </View>
        )}

        {isScanning && (
          <TouchableOpacity style={styles.captureButton} onPress={handleTakePicture}>
            <Icon name="camera" size={30} color="#fff" />
          </TouchableOpacity>
        )}

        <TouchableOpacity
          style={[styles.continueButton, !scannedImage && styles.disabledButton]}
          onPress={handleContinue}
          disabled={!scannedImage}
        >
          <Text style={styles.continueButtonText}>继续</Text>
        </TouchableOpacity>
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: 20,
    paddingVertical: 40,
  },
  permissionContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 30,
  },
  permissionText: {
    fontSize: 18,
    color: '#fff',
    textAlign: 'center',
    marginBottom: 20,
  },
  permissionButton: {
    backgroundColor: '#4CAF50',
    borderRadius: 25,
    paddingVertical: 15,
    paddingHorizontal: 30,
  },
  permissionButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 10,
  },
  subtitle: {
    fontSize: 16,
    color: '#a0a0a0',
    textAlign: 'center',
    marginBottom: 30,
  },
  cameraContainer: {
    height: 300,
    borderRadius: 15,
    overflow: 'hidden',
    marginBottom: 30,
  },
  camera: {
    flex: 1,
  },
  cameraOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scanFrame: {
    width: 250,
    height: 150,
    borderWidth: 2,
    borderColor: '#4CAF50',
    borderRadius: 10,
    borderStyle: 'dashed',
  },
  scanHint: {
    color: '#fff',
    fontSize: 16,
    marginTop: 20,
  },
  previewContainer: {
    height: 300,
    borderRadius: 15,
    overflow: 'hidden',
    marginBottom: 30,
  },
  previewImage: {
    width: '100%',
    height: '100%',
  },
  retakeButton: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    borderRadius: 20,
    padding: 10,
    flexDirection: 'row',
    alignItems: 'center',
  },
  retakeText: {
    color: '#fff',
    marginLeft: 5,
  },
  captureButton: {
    backgroundColor: '#4CAF50',
    width: 70,
    height: 70,
    borderRadius: 35,
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
    marginBottom: 30,
  },
  continueButton: {
    backgroundColor: '#4CAF50',
    borderRadius: 25,
    paddingVertical: 15,
    alignItems: 'center',
    marginTop: 20,
  },
  disabledButton: {
    backgroundColor: '#666',
  },
  continueButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default DocumentScanScreen;
